package com.itfh_wanwan;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

public class A01_注册 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String um = req.getParameter("username");
        String pd = req.getParameter("password");
        String pd1 = req.getParameter("password1");

        if (pd.equals(pd1)){
            Connection rt=null;
            try {
//                连接数据库
                Class.forName("com.mysql.jdbc.Driver");
                //Class.forName("com.mysql.jdbc.Driver");
                 rt = DriverManager.getConnection
                        ("jdbc:mysql://127.0.0.1:3306/fh_day03",
                                "root", "123456");
//            将账号密码存到数据库
                 String sql="insert into user (username,psaawrod) values(?,?)";
//            获取预编译对象
                PreparedStatement pt = rt.prepareStatement(sql);
//            给占位符赋值
                pt.setString(1,um);
                pt.setString(2,pd);
//            执行sql语句
                int i = pt.executeUpdate();
//            转发到登录页面
//            定时刷新
                resp.setHeader("Refresh","4;URL=dl.jsp");
//            告诉用户注册成功
                resp.getWriter().write("<p style='color:green'>注册成功,4秒后跳转到登录页面</p>");
//            然后提示成功将请求转发到登录页面
            } catch (Exception e) {
                         e.printStackTrace();
                        }  finally {
                if (rt!=null){
                    try{
                      rt.close();
                    } catch (SQLException throwables) {
                        throwables.printStackTrace();
                    }
                }
            }
                 }else {
//            两次密码输入不一致
//            首先提示密码不一致
            req.setAttribute("smg","密码输不一致");
//            然后转发到注册页面
            req.getRequestDispatcher("/registr.jsp").forward(req,resp);
             }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
